package com.share.admin.web;

import com.share.admin.model.vo.SseMsg;
import com.share.admin.service.SseEmitterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * 模拟 websocket的技术,服务端主动给向客户端推送数据
 */
@RestController
@RequestMapping("/sse")
public class SseController {
    @Autowired
    private SseEmitterService sseEmitterService;


    @CrossOrigin
    @GetMapping("/createConnect")
    public SseEmitter createConnect(String clientId) {
        return sseEmitterService.createConnect(clientId);
    }

    @CrossOrigin
    @PostMapping("/broadcast")
    public void sendMessageToAllClient(@RequestBody(required = false) String msg) {
        sseEmitterService.sendMessageToAllClient(msg);
    }

    @CrossOrigin
    @PostMapping("/sendMessage")
    public void sendMessageToOneClient(@RequestBody(required = false) SseMsg messageVo) {
        if (messageVo.getClientId().isEmpty()) {
            return;
        }
        sseEmitterService.sendMessageToOneClient(messageVo.getClientId(), messageVo.getData());
    }

    @CrossOrigin
    @GetMapping("/closeConnect")
    public void closeConnect(@RequestParam(required = true) String clientId) {
        sseEmitterService.closeConnect(clientId);
    }
}
